package it.fuesi.expired.api.controllers.base;

import it.fuesi.expired.adapters.base.IAdapter;
import it.fuesi.expired.adapters.base.IAdapterSession;
import it.fuesi.expired.adapters.mongo.MongoAdapter;
import it.fuesi.expired.api.base.CrudService;
import it.fuesi.expired.helpers.ClassResolverHelper;
import it.fuesi.expired.model.base.ErrorModel;
import it.fuesi.expired.model.base.IModel;
import it.fuesi.expired.model.base.ModelCollection;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;

public abstract class ACrudController<T extends IModel> extends ABaseController implements CrudService<T> {

protected static final IAdapter adapter = new MongoAdapter(); //FIXME
	
	public ModelCollection<T> getAll() throws Exception{
		IAdapterSession session = null;
		
		try{
			session = adapter.openSession();
			
			return session.getAll(getModelClass());
		}finally{
			if(session != null)
				session.close();
		}
	}
	
	public T get(@PathVariable String _id) throws Exception{
		IAdapterSession session = null;
		
		try{
			session = adapter.openSession();
			
			return session.get(getModelClass(), _id);
		}finally{
			if(session != null)
				session.close();
		}
	}
	
	@Override
	public T add(@RequestBody T model) throws Exception{
		IAdapterSession session = null;
		
		try{
			session = adapter.openSession();
			
			return session.put(model);
		}finally{
			if(session != null)
				session.close();
		}
	}
	
	public T update(@RequestBody T model) throws Exception{
		IAdapterSession session = null;
		
		try{
			session = adapter.openSession();
			
			return session.update(model);
		}finally{
			if(session != null)
				session.close();
		}
	}
	
	public ErrorModel delete(@PathVariable String _id) throws Exception{
		IAdapterSession session = null;
		final ErrorModel error = new ErrorModel();
		error.set_id(_id);
		try{
			session = adapter.openSession();
			
			session.delete(getModelClass(), _id);
			
			error.setSuccess(true);
		}finally{
			if(session != null)
				session.close();
		}
		
		return error;
		
	}
	
	public ErrorModel deleteAll() throws Exception{
		IAdapterSession session = null;
		final ErrorModel error = new ErrorModel();
		
		try{
			session = adapter.openSession();
			
			session.delete(getModelClass());
			
			error.setSuccess(true);
		}finally{
			if(session != null)
				session.close();
		}
		
		return error;
		
	}
	
	private Class<T> getModelClass()
    {
        return (Class<T>) ClassResolverHelper.getTypeArguments(ACrudController.class, getClass()).get(0);
    }
	
	
	
}
